package com.easy.carpanel.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.easy.carpanel.R;

import androidx.annotation.Nullable;


public class TextProgressBar extends androidx.appcompat.widget.AppCompatSeekBar {


    private int min;
    private int max;
    private int current;
    private String unit;
    private Paint mPaint;

    public TextProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextProgressBar(Context context) {
        this(context, null);
    }
    public TextProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setClickable(false);
        this.setFocusable(false);
        this.setOnTouchListener((v, event) -> true);
        initAttrs(context, attrs);
        initPaint();
    }

    private void initAttrs(Context context, AttributeSet attrs){
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.TextProgressBar);
        min = attributes.getInt(R.styleable.TextProgressBar_min, 0);
        max = attributes.getInt(R.styleable.TextProgressBar_max, 100);
        current = attributes.getInt(R.styleable.TextProgressBar_current, 0);
        unit = attributes.getString(R.styleable.TextProgressBar_unit);
        if(unit == null){
            unit = "";
        }
        this.setCurrent(current);
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.WHITE);
        mPaint.setDither(true);
        mPaint.setTextSize(sp2px(5));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float width = getWidth();
        float offset = getHeight() / 2f;
        float maxW = width - getPaddingRight() - offset;
        float minW = getPaddingLeft();
        float progressRatio =  (float) (current - min) / (max - min);
        canvas.drawText(current + unit, minW + (maxW - minW) * progressRatio , offset * 1.5f, mPaint);
        canvas.drawText(max + unit, maxW , offset * 1.5f, mPaint);
        canvas.drawText(min + unit, minW, offset * 1.5f, mPaint);
        super.onDraw(canvas);
    }


    public void setCurrent(int current) {
        this.current = current;
    }

    protected float sp2px(float spVal) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
    }
}

